package com.lehecai.core.search.api;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SearchApiRequestAggregate {

    private SearchApiRequestGet get;

    private List<SearchApiRequestAggregateItem> aggregateItemList = new ArrayList<SearchApiRequestAggregateItem>();

    private String[] group;

    public SearchApiRequestAggregate() {

    }

    public void addAggreate(String operation, String target, String as) {
        SearchApiRequestAggregateItem aggregateItem = new SearchApiRequestAggregateItem(operation, target, as);
        this.addAggreate(aggregateItem);
    }

    public void addAggreate(SearchApiRequestAggregateItem aggregateItem) {
        this.aggregateItemList.add(aggregateItem);
    }

	public JSON toJSON() {
        JSONObject jsonObject = new JSONObject();

        JSONArray aggregateArray = new JSONArray();

        for (SearchApiRequestAggregateItem aggregateItem : this.aggregateItemList) {
            aggregateArray.add(aggregateItem.toJSON());
        }

        jsonObject.put(SearchApiConstant.API_PARAMETER_AGGREGATE, aggregateArray);

        if (this.group != null && this.group.length > 0) {
            jsonObject.put(SearchApiConstant.API_PARAMETER_AGGREGATE_GROUP, this.group);
        }

        jsonObject.put(SearchApiConstant.API_PARAMETER_GET, this.get.toJSON());

        return jsonObject;
    }

    public SearchApiRequestGet getGet() {
        return get;
    }

    public void setGet(SearchApiRequestGet get) {
        this.get = get;
    }

    public String[] getGroup() {
        return group;
    }

    public void setGroup(String[] group) {
        this.group = group;
    }

    public List<SearchApiRequestAggregateItem> getAggregateItemList() {
        return aggregateItemList;
    }

    public void setAggregateItemList(List<SearchApiRequestAggregateItem> aggregateItemList) {
        this.aggregateItemList = aggregateItemList;
    }
}
